import { defineStore } from 'pinia';
import { store } from '/@/store';
import { Persistent } from '/@/utils/cache/persistent';
import { authPropertiesModel, encryptPropertiesModel } from '/@/api/sys/model/propertiesModel';
import { getAuthProperties, getEncryptProperties } from '/@/api/sys/properties';
import { AUTH_PROPERTIES_CACHE_KEY, ENCRYPT_PROPERTIES_CACHE_KEY } from '/@/enums/cacheEnum';

interface PropertiesState {
    auth: authPropertiesModel,
    encrypt: encryptPropertiesModel
}

export const usePropertiesStore = defineStore({
    id: 'properties',
    state: (): PropertiesState => ({
        auth: {
            enable: false,
            local: true,
            sync: true,
            iscLoginUrl: '',
            iscLogoutUrl: '',
        },
        encrypt: {
            enable: false,
            key: '',
            excludeUrls: [],
        }
    }),
    getters: {
        getAuthProperties(): authPropertiesModel {
            return Persistent.getLocal(AUTH_PROPERTIES_CACHE_KEY) || this.auth;
        },
        getEncryptProperties(): encryptPropertiesModel {
            return Persistent.getLocal(ENCRYPT_PROPERTIES_CACHE_KEY) || this.encrypt;
        },
    },
    actions: {
        setAuthProperties(authProperties: authPropertiesModel) {
            this.auth = authProperties;
            Persistent.setLocal(AUTH_PROPERTIES_CACHE_KEY, authProperties);
        },
        setEncryptProperties(encryptProperties: encryptPropertiesModel) {
            this.encrypt = encryptProperties;
            Persistent.setLocal(ENCRYPT_PROPERTIES_CACHE_KEY, encryptProperties);
        },
        async setAllPropertise() {
            if (!Persistent.getLocal(AUTH_PROPERTIES_CACHE_KEY)) {
                let encrptResult = await getEncryptProperties();
                this.setEncryptProperties(encrptResult.data);
            }
            if (!Persistent.getLocal(ENCRYPT_PROPERTIES_CACHE_KEY)) {
                let authResult = await getAuthProperties();
                this.setAuthProperties(authResult.data);
            }
        },
        resetAllProperties() {
            Persistent.removeLocal(AUTH_PROPERTIES_CACHE_KEY);
            Persistent.removeLocal(ENCRYPT_PROPERTIES_CACHE_KEY);
            this.setAllPropertise();
        }
    }
});

export function usePropertiesStoreWithOut() {
    return usePropertiesStore(store);
}